package com.maxima.attendance.interceptors;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.maxima.attendance.constants.Constants;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class SessionValidator extends AbstractInterceptor {
	private static final long serialVersionUID = 1L;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		String validateSession = validateSession();
		if (!validateSession.equals(Constants.ERROR)) {
			return !invocation.invokeActionOnly().equals(Constants.ERROR) ? validateSession : Constants.ERROR;
		}
		return Constants.ERROR;
	}

	public static String validateSession() {
		return validateAdminSession() ? Constants.ADMIN_LOGGEDIN : (validateUserSession() ? Constants.USER_LOGGEDIN : Constants.ERROR);
	}

	public static boolean validateUserSession() {
		Object obj = ServletActionContext.getRequest().getSession().getAttribute(Constants.USER_LOGIN);
		return obj != null ? (Boolean) obj : false;
	}

	public static boolean validateAdminSession() {
		Object obj = ServletActionContext.getRequest().getSession().getAttribute(Constants.ADMIN_LOGIN);
		return obj != null ? (Boolean) obj : false;
	}

	public static void clearSession() {
		HttpSession session = ServletActionContext.getRequest().getSession(false);
		if (session != null) {
			session.invalidate();
		}
	}

	public static boolean checkSession() {
		HttpSession session = ServletActionContext.getRequest().getSession(false);
		return session != null;
	}
}
